package com.sservice.base.utils;

import com.sservice.base.utils.encrypt.CodecUtils;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MyEncrypt extends CodecUtils {
    public static final String KEY_SHA = "SHA";
    public static final String KEY_MD5 = "MD5";
    public static final String KEY_MAC = "HmacMD5";

    protected MyEncrypt() {
        super();
    }

    // sun不推荐使用它们自己的base64,用apache的挺好

    /**
     * BASE64解密
     */
    public static byte[] decryptBASE64(byte[] dest) {
        if (dest == null) {
            return null;
        }
        return Base64.decodeBase64(dest);
    }

    /**
     * BASE64加密
     */
    public static byte[] encryptBASE64(byte[] origin) {
        if (origin == null) {
            return null;
        }
        return Base64.encodeBase64(origin);
    }

    /**
     * MD5加密
     *
     * @throws NoSuchAlgorithmException
     */
    public static byte[] encryptMD5(byte[] data)
            throws NoSuchAlgorithmException {
        if (data == null) {
            return null;
        }
        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
        md5.update(data);
        return md5.digest();
    }

    /**
     * SHA加密
     *
     * @throws NoSuchAlgorithmException
     */
    public static byte[] encryptSHA(byte[] data)
            throws NoSuchAlgorithmException {
        if (data == null) {
            return null;
        }
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
        sha.update(data);
        return sha.digest();
    }

    /**
     * 初始化HMAC密钥
     *
     * @throws NoSuchAlgorithmException
     */
    public static String initMacKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
        SecretKey secretKey = keyGenerator.generateKey();
        return new String(encryptBASE64(secretKey.getEncoded()));
    }

    /**
     * HMAC加密
     *
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static byte[] encryptHMAC(byte[] data, String key)
            throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKey secretKey = new SecretKeySpec(decryptBASE64(key.getBytes()),
                KEY_MAC);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);

    }

    /***
     * 系统加密算法
     * @param plainPassword 原始密码
     * @return
     */
    public static String encryptPwd(String plainPassword) {
        try {
            return md5Encode(plainPassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String md5Encode(String inStr) throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//        String data = "z9WXOfTa#kGGHeMpb7eXT11fdQIfiMldFQBdZu3cJf";
//        String data = "z9WXOfTa#kGGHeMpb7eXT11fdQIfiMldFQBdZu3cJf";
//        String data = "tVa3s3pkZ8ywoJQLq/hLKw==";
        String data = "i52+cs2mlirBktPvXJI8H//Lr2Smr01lVVb1JbBnOwRdwhEZDmbyn0X8w1+ZUJR8";
//        String data = "MD$EStt4!6eSE";
//        String key = KEY_DES; //
        String key = "DaLZ2tT1+Hu2naqYTWx1XWEE7YLHEW/oVhnGfb1+d5RetQL1iGaXcQbCtHw3zP2MsnFPIpE8Wy4aKcK1TfRvVg=="; //
//        String key = "DaLZ2tT1+Hu2naqYTWx1XWEE7YLHEW/oVhnGfb1+d5RetQL1iGaXcQbCtHw3zP2MsnFPIpE8Wy4aKcK1TfRvVg=="; //
//        System.out.println(md5Encode(data));
//        System.out.println(desEncryp(data, MyEncrypt.KEY_DES).toString());
        System.out.println(desDecrypt(data, MyEncrypt.KEY_DES).toString());//
        System.out.println(desDecrypt(desEncryp(data, key), key));
        System.out.println(desDecrypt(data, key));
//
//        System.out.println(new BigInteger(encryptMD5(data.getBytes())).toString());
//        System.out.println(encryptSHA(data.getBytes()).toString());
        System.out.println(MyEncrypt.encryptPwd(encryptMD5("123456".getBytes()).toString()));
        System.out.println(MyEncrypt.encryptPwd("123456"));
//        System.out.println(MyEncrypt.encryptPwd("e10adc3949ba59abbe56e057f20f883e"));
//        System.out.println(MyEncrypt.encryptPwd("e10adc3949ba59abbe56e057f20f883e"));
//
//        System.out.println(new BigInteger(encryptHMAC(data.getBytes(), initMacKey())).toString());
    }

}
